from flask import Flask, request, jsonify, session
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
import random
import time

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于会话加密
CORS(app)  # 启用 CORS

# 假设的用户数据库
users = {}

# 假设的数据存储
data_storage = []

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return jsonify({'error': 'Missing username or password'}), 400
    if username in users:
        return jsonify({'error': 'User already exists'}), 400
    hashed_password = generate_password_hash(password)
    users[username] = hashed_password
    return jsonify({'message': 'User registered successfully'}), 201

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return jsonify({'error': 'Missing username or password'}), 400
    if username not in users or not check_password_hash(users[username], password):
        return jsonify({'error': 'Invalid credentials'}), 401
    session['username'] = username  # 将用户名存储在会话中
    return jsonify({'message': 'Logged in successfully'}), 200

@app.route('/logout', methods=['POST'])
def logout():
    session.pop('username', None)  # 从会话中移除用户名
    return jsonify({'message': 'Logged out successfully'}), 200

@app.route('/push', methods=['POST'])
def push_data():
    data = {
        'timestamp': int(time.time()),
        'building': random.randint(1, 10),
        'charge': random.randint(100, 500),
        'consumption': random.randint(100, 500)
    }
    data_storage.append(data)
    return jsonify(data), 201

@app.route('/data', methods=['GET'])
def get_data():
    return jsonify(data_storage)

@app.route('/receive', methods=['POST'])
def receive_data():
    data = request.get_json()
    analyzed_data = analyze_data(data)
    save_data_to_db(analyzed_data)
    return jsonify(analyzed_data), 201

def analyze_data(data):
    average_charge = sum(d['charge'] for d in data) / len(data)
    average_consumption = sum(d['consumption'] for d in data) / len(data)
    return {
        'average_charge': average_charge,
        'average_consumption': average_consumption
    }

def save_data_to_db(data):
    # 这里可以实现将数据保存到数据库的逻辑
    print("Data saved to DB:", data)

@app.route('/')
def home():
    return "Welcome to the Smart Campus Project!"

if __name__ == '__main__':
    app.run(debug=True)

#/register 和/login路由处理用户的注册和登录请求
#/push路由模拟推送数据，并将数据存储在data_storage列表中
#/data路由返回所有推送的数据
#/receive路由接受数据，调用analyze_data函数进行数据分析，并将分析结果存储到数据库
#analyze_data函数计算充电量和用电量的平均值